﻿using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace K9Nano.Authorization;

public static class ControllerActionDescriptorExtensions
{
    public static string ToActionPrimaryId(this ControllerActionDescriptor controllerAction)
    {
        var verb = controllerAction.ActionConstraints?
                      .OfType<HttpMethodActionConstraint>()
                      .FirstOrDefault()?
                      .HttpMethods
                      .FirstOrDefault();

        if (string.IsNullOrEmpty(verb))
        {
            throw new Exception("HttpMethod不能为空: " + controllerAction.DisplayName);
        }
        var route = controllerAction.AttributeRouteInfo?.Template;

        if (route is null)
        {
            throw new Exception("路由不能为空");
        }

        return verb + '-' + route;
    }
}
